package com.huika.dealontop.control.pay.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.pay.utils.BasePay;
import com.huika.dealontop.control.pay.utils.LinePay;
import com.huika.dealontop.control.pay.utils.OmisePay;
import com.huika.dealontop.control.pay.utils.PayPalPay;
import com.huika.dealontop.control.pay.utils.PaysBuyPay;
import com.huika.dealontop.support.domain.OrderProcessBean;
import com.huika.dealontop.support.domain.UserModel;
import com.huika.dealontop.support.event.PayEvent;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.views.TitleBarHelper;
import com.huika.huikalib.utils.MoneyShowTool;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;

/**
 * Description:选择支付方式：omise   paypal  line pay
 * Created by zhouweiyong on 2015/11/19.
 */
public class ChoosePayModesActivity extends BaseAct {
    private TextView tv_order_num_pac, tv_phone_pac, tv_total_money_pac;
    private LinearLayout layout_content, layout_omise_pac, layout_paypal_pac, layout_line_pac,layout_paysbuy_pac,layout_phone_pac;
    private ImageView cb_omise_pac, cb_paypal_pac, cb_line_pac,cb_paysbuy_pac;
    private TextView tv_omise_pac, tv_paypal_pac, tv_line_pac,tv_paysbuy_pac;
    private Button btn_pac;
    private ArrayList<ImageView> checks;
    private ArrayList<TextView> selectTvs;
    private int payMode;//0:omise  1:paypal  2:line pay
    private OrderProcessBean orderProcessBean;
    private String paymentOrderId;
    private UserModel userModel;
    private BasePay basePay;
    private PayPalPay payPalPay;
    private String orderId;
    private double totalPrice;
    private String phone;
    private String userId;

    @Override
    protected void initData() {
        userModel = GlobalApp.userModel;
        Intent intent = getIntent();
        paymentOrderId = intent.getStringExtra(BasePay.PAYORDERNO);
        orderId = intent.getStringExtra(BasePay.ORDERNO);
        phone = intent.getStringExtra(BasePay.PHONE);
        userId = intent.getStringExtra(BasePay.USERID);
        totalPrice =  intent.getDoubleExtra(BasePay.TOTALMONEY, 0);
        if (TextUtils.isEmpty(phone) || "0".equals(phone)) {
            phone = userModel.getPhone();
        }
        if (TextUtils.isEmpty(userId) || "0".equals(userId)) {
            userId = String.valueOf(userModel.getUserID());
        }
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.pay_activity_choose);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initWidget() {
        TitleBarHelper titleBarHelper = new TitleBarHelper(aty, R.string.title_choose_pay);
        titleBarHelper.setLeftMsg("");
        checks = new ArrayList<ImageView>();
        selectTvs = new ArrayList<TextView>();
        layout_content = (LinearLayout) findViewById(R.id.layout_content);
        tv_order_num_pac = (TextView) findViewById(R.id.tv_order_num_pac);
        layout_phone_pac = (LinearLayout) findViewById(R.id.layout_phone_pac);
        tv_phone_pac = (TextView) findViewById(R.id.tv_phone_pac);
        tv_total_money_pac = (TextView) findViewById(R.id.tv_total_money_pac);
        layout_omise_pac = (LinearLayout) findViewById(R.id.layout_omise_pac);
        layout_paypal_pac = (LinearLayout) findViewById(R.id.layout_paypal_pac);
        layout_line_pac = (LinearLayout) findViewById(R.id.layout_line_pac);
        layout_paysbuy_pac = (LinearLayout) findViewById(R.id.layout_paysbuy_pac);
        cb_omise_pac = (ImageView) findViewById(R.id.cb_omise_pac);
        cb_paypal_pac = (ImageView) findViewById(R.id.cb_paypal_pac);
        cb_line_pac = (ImageView) findViewById(R.id.cb_line_pac);
        cb_paysbuy_pac = (ImageView) findViewById(R.id.cb_paysbuy_pac);
        tv_omise_pac = (TextView) findViewById(R.id.tv_omise_pac);
        tv_paypal_pac = (TextView) findViewById(R.id.tv_paypal_pac);
        tv_line_pac = (TextView) findViewById(R.id.tv_line_pac);
        tv_paysbuy_pac = (TextView) findViewById(R.id.tv_paysbuy_pac);
        btn_pac = (Button) findViewById(R.id.btn_pac);
        checks.add(cb_omise_pac);
        checks.add(cb_paypal_pac);
        checks.add(cb_line_pac);
        checks.add(cb_paysbuy_pac);
        selectTvs.add(tv_omise_pac);
        selectTvs.add(tv_paypal_pac);
        selectTvs.add(tv_line_pac);
        selectTvs.add(tv_paysbuy_pac);
        layout_omise_pac.setOnClickListener(this);
        layout_paypal_pac.setOnClickListener(this);
        layout_line_pac.setOnClickListener(this);
        layout_paysbuy_pac.setOnClickListener(this);
        btn_pac.setOnClickListener(this);

        payPalPay = new PayPalPay(this, mHandler);
        payPalPay.startServer();
        if (TextUtils.isEmpty(orderId)) {
            startOverallLoading(layout_content);
            orderProcessNet();
        } else {
            refreshUi();
        }
    }

    private void orderProcessNet() {
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("paymentOrderId", paymentOrderId);
        FormResultRequest<OrderProcessBean> request = new FormResultRequest<OrderProcessBean>(UrlConstants.ORDERPROCESSRESULT, new Response.Listener<RequestResult<OrderProcessBean>>() {
            @Override
            public void onResponse(RequestResult<OrderProcessBean> arg0) {
                if (arg0.flag == 1) {
                    orderProcessBean = arg0.getRs();
                    switch (orderProcessBean.getStatus()) {
                        case 0://订单处理成功
                            stopOverallLoading();
                            orderId = orderProcessBean.getOrderID();
                            totalPrice = orderProcessBean.getProductAmount();
                            refreshUi();
                            break;
                        case -1://订单处理失败
                            showActivity(ChoosePayModesActivity.this, PayFailActivity.class);
                            break;
                        default://其它原因,需再次联网查询
                            orderProcessNet();
                            break;
                    }
                } else {
                    orderProcessNet();
                }
            }
        }, this, new TypeToken<RequestResult<OrderProcessBean>>() {
        }.getType());
        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }

    private void refreshUi() {
        tv_order_num_pac.setText(orderId);
        if (!TextUtils.isEmpty(phone)) {
            tv_phone_pac.setText(String.format("%s****%s", phone.substring(0, 3), phone.substring(7, 10)));
        } else {
            layout_phone_pac.setVisibility(View.GONE);
        }
        tv_total_money_pac.setText(String.format(getString(R.string.common_money), MoneyShowTool.twolastDF(totalPrice)));
        if (totalPrice>=20){
            layout_omise_pac.performClick();
        }else{
            layout_paypal_pac.performClick();
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BasePay.PAY_SUCCESS:
                    showActivity(ChoosePayModesActivity.this, PaySuccessActivity.class);
                    break;
                case BasePay.PAY_FAILURE:
                    showActivity(ChoosePayModesActivity.this, PayFailActivity.class);
                    break;
            }
        }
    };

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.layout_omise_pac:
                payMode = BasePay.PAY_MODE_OMISE;
                selectPayMode(0);
                break;
            case R.id.layout_paypal_pac:
                payMode = BasePay.PAY_MODE_PAYPAL;
                selectPayMode(1);
                break;
            case R.id.layout_line_pac:
                payMode = BasePay.PAY_MODE_LINE;
                selectPayMode(2);
                break;
            case R.id.layout_paysbuy_pac:
                payMode = BasePay.PAY_MODE_PAYSBUY;
                selectPayMode(3);
                break;
            case R.id.btn_pac:
                chosePayMode(payMode);
                break;
        }
    }

    private void selectPayMode(int positon) {
        for (int i = 0; i < checks.size(); i++) {
            if (i != positon) {
                checks.get(i).setSelected(false);
            } else {
                checks.get(i).setSelected(true);
            }
        }
        for (int j = 0; j < selectTvs.size(); j++) {
            if (j != positon) {
                selectTvs.get(j).setText(getString(R.string.pay_select));
            } else {
                selectTvs.get(j).setText(getString(R.string.pay_cancle));
            }
        }
    }

    public void chosePayMode(int payMode) {
        switch (payMode) {
            case BasePay.PAY_MODE_OMISE:
                if (totalPrice<20){
                    showToastMsg(R.string.pay_omise_limit);
                    return;
                }
                basePay = new OmisePay(this, true);
                break;
            case BasePay.PAY_MODE_PAYPAL:
                basePay = payPalPay;
                break;
            case BasePay.PAY_MODE_LINE:
                basePay = new LinePay(this);
                break;
            case BasePay.PAY_MODE_PAYSBUY:
                basePay = new PaysBuyPay(this);
                break;
        }
        if (!TextUtils.isEmpty(phone)) {
            basePay.setPhone(phone);
        }
        basePay.setUserId(userId);
        basePay.setOrderNo(orderId);
        basePay.setPayMethod(payMode);
        basePay.setPayOrderNo(paymentOrderId);
        basePay.setTotalMoney(totalPrice);
        basePay.pay();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PayPalPay.REQUEST_CODE_PAYMENT) {
            payPalPay.receiveResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        payPalPay.stopServer();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(PayEvent eventBean) {
        this.finish();
    }

}
